package com.example.uploadminio.service;
/**
 * 开机自启
 */
import java.io.File;
import java.io.IOException;

/**
 * Windows 平台开机自启管理器
 */
public class StartupManager {

    private static final String RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";

    /**
     * 启用开机自启
     *
     * @param appName  注册表中的应用名称
     * @param exePath  可执行文件路径
     */
    public static void enable(String appName, String exePath) {
        try {
            // 路径带空格时要加引号
            if (!exePath.startsWith("\"")) {
                exePath = "\"" + exePath + "\"";
            }

            String cmd = String.format("reg add \"%s\" /v \"%s\" /d %s /f",
                    RUN_KEY, appName, exePath);
            runCommand(cmd);
            System.out.println("已设置开机自启: " + appName + " -> " + exePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 禁用开机自启
     *
     * @param appName 注册表中的应用名称
     */
    public static void disable(String appName) {
        try {
            String cmd = String.format("reg delete \"%s\" /v \"%s\" /f",
                    RUN_KEY, appName);
            runCommand(cmd);
            System.out.println("已取消开机自启: " + appName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查是否已启用开机自启
     */
    public static boolean isEnabled(String appName) {
        try {
            String cmd = String.format("reg query \"%s\" /v \"%s\"",
                    RUN_KEY, appName);
            Process process = runCommand(cmd);
            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (Exception e) {
            return false;
        }
    }

    private static Process runCommand(String cmd) throws IOException {
        return Runtime.getRuntime().exec(new String[]{"cmd", "/c", cmd});
    }
}
